<template>
  <form>
    <div class="mb-3">
      <label for="exampleInputEmail1" class="form-label">邮箱地址</label>
      <input
        type="email"
        class="form-control"
        id="exampleInputEmail1"
        aria-describedby="emailHelp"
        v-model="inputRef.value"
        @blur="rulesBlur"
      />
      <div id="emailHelp" class="form-text" v-if="inputRef.error">
        {{inputRef.message}}
      </div>
    </div>
    <div class="mb-3">
      <label for="exampleInputPassword1" class="form-label">密码</label>
      <input type="password" class="form-control" id="exampleInputPassword1" />
    </div>
  </form>
</template>

<script lang="ts">
import { defineComponent, PropType, reactive } from 'vue'
interface RuleProp {
  type: 'requied' | 'email';
  message: string;
}
export type RulesProp = RuleProp[]
export default defineComponent({
  name: 'VaildateInput',
  props: {
    rules: Array as PropType<RulesProp>
  },
  setup (props) {
    const inputRef = reactive({
      value: '',
      error: false,
      message: ''
    })
    const rulesReg = new RegExp('^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$')
    const rulesBlur = () => {
      console.log(123)
      if (props.rules) {
        const addRules = props.rules.every(rules => {
          let passed = true
          inputRef.message = rules.message
          switch (rules.type) {
            case 'requied':
              passed = inputRef.value.trim() !== ''
              break
            case 'email':
              passed = rulesReg.test(inputRef.value)
              break
            default:
              break
          }
          return passed
        })
        inputRef.error = !addRules
      }
    }
    return {
      inputRef,
      rulesBlur
    }
  }
})
</script>

<style></style>
